package com.coolingme.register05.enum01;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化测试
 * <p>
 * 不会被序列化破坏，枚举式单例在静态代码块中就给 INSTANCE 进行了赋值，是饿汉式单例的实现
 *
 * @author wangyue
 * @date 2020/9/29 15:09
 */
public class SerializableTest {

    public static void main(String[] args) {
        Object object = "Hello,World  努力，奋斗";
//        Object object = new Object();

        EnumSingleton instance1 = EnumSingleton.getInstance();
        instance1.setData(object);
        EnumSingleton instance2;

        String objUrl = System.getProperty("user.dir") + "\\pattern-02-singleton\\src\\main\\java\\com\\coolingme\\register05\\enum01\\Serializable.obj";
        System.out.println("序列化对象地址：" + objUrl);

        try {
            // 写
            FileOutputStream fos = new FileOutputStream(objUrl);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(instance1);
            oos.flush();
            oos.close();

            // 读
            FileInputStream fis = new FileInputStream(objUrl);
            ObjectInputStream ois = new ObjectInputStream(fis);
            instance2 = (EnumSingleton) ois.readObject();
            ois.close();

            System.out.println(instance1 + "  " + instance1.getData());
            System.out.println(instance2 + "  " + instance2.getData());
            System.out.println(instance1 == instance2);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
